
from email.quoprimime import header_check
from typing import List
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, emit, join_room
from functools import wraps
import sys
import os
import asyncio


# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, project_root)
# print(project_root)

from src.backend.task_sever import TaskServer
from src.backend.data_bridge import DataBridge

class SocketServer:
    def __init__(self, app: Flask, socketio: SocketIO, 
                 task_server: TaskServer,
                 data_bridge: DataBridge
                 ):
        self.app = app
        self.socketio = socketio
        # Todo
        self.task_server = task_server
        self.data_bridge = data_bridge
        self.register_routes()
        self.register_socketio_events()

    def register_routes(self):
        @self.app.route('/')
        def index():
            return render_template('index.html')

        @self.app.route('/api/test', methods=['POST'])
        def api_test():
            data = request.json
            return jsonify({'msg': '收到了', 'data': data})
        
        # 添加调试页面路由
        @self.app.route('/debug')
        def debug():
            return render_template('debug.html')
        
        @self.app.route('/debug/modify')
        def debug_modify():
            return render_template('modify.html')
        
        @self.app.route('/debug/tree')
        def debug_tree():
            return render_template('tree.html')
        
        @self.app.route('/debug/detail')
        def debug_detail():
            return render_template('detail.html')

    def register_socketio_events(self):
        @self.socketio.on('connect')
        def handle_connect():
            print('[Socket] 用户连接')
            emit('server_message', {'msg': '欢迎连接'})

        @self.socketio.on('chat_message')
        def handle_chat_message(data):
            msg = data.get('msg')
            print('[Socket] 收到消息:', msg)
            emit('chat_message', {'msg': msg}, broadcast=True)

        @self.socketio.on('join_room')
        def handle_join(data):
            room = data.get('room')
            join_room(room)
            emit('server_message', {'msg': f'你加入了房间 {room}'}, room=room)
        
        @self.socketio.on('test_event')
        def handle_test_event(data):
            print('收到测试事件:', data)
            emit('test_event', {'reply': '测试事件收到了', 'original_data': data})

        @self.socketio.on('ping')
        def handle_ping(data):
            print('收到ping:', data)
            emit('pong', {'msg': 'pong', 'timestamp': data.get('timestamp')})

        @self.socketio.on('custom_event')
        def handle_custom_event(data):
            print('收到自定义事件:', data)
            emit('server_received', {'msg': '自定义事件处理完成', 'data': data})


        @self.socketio.on('command_event')
        def handle_command_event(data):
            print('收到命令事件:', data)
            emit('server_received', {'msg': '命令事件处理完成', 'data': data})
            # Todo
            results = asyncio.run(self.task_server.add_command_event(data))
            # print(f"=====================results================== \n{results}")
            fronted_json = self.data_bridge.parse_to_frontend(data,results)
            # print(f"=====================fronted_json================== \n{fronted_json}")

            emit('event_result', fronted_json)
        
        @self.socketio.on('login_remote')
        def handle_login_remote(data):
            print('收到登录事件:', data)
            emit('server_received', {'msg': '登录事件处理完成', 'data': data})
            # Todo
            success,msg = asyncio.run(self.task_server.login_remote(data))

            if success:
                emit('connection_result', {'success': True, 'msg': msg, 'data': data})
            else:
                emit('connection_result', {'success': False, 'msg': msg, 'data': data})

        @self.socketio.on('check_health')
        def handle_check_health(data):
            print('收到远程连接健康检查事件:', data)
            emit('server_received', {'msg': '健康检查事件处理完成', 'data': data})
            # Todo
            health_report = self.task_server.check_health()
            emit('server_message', {'msg': '健康检查事件处理完成', 'data': health_report})


if __name__ == '__main__':
    # ------------------------- 项目入口 -------------------------
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'your-secret-key'
    socketio = SocketIO(app, cors_allowed_origins='*')
    task_server = TaskServer()
    data_bridge = DataBridge()


    asyncio.run(task_server.login_remote_preset())


    # 注册你的路由和事件模块
    my_server = SocketServer(app, socketio, task_server, data_bridge)


    socketio.run(app, host='127.0.0.1', port=7712, debug=True)